package com.xianyun.site.iblog.user.executor.handle.impl;

import com.xianyun.common.core.utils.FormatUtils;
import com.xianyun.site.iblog.common.core.exception.LoginCheckErrorException;
import com.xianyun.site.iblog.common.core.exception.UserNotRegisterException;
import com.xianyun.site.iblog.convertor.SystemUserConvertor;
import com.xianyun.site.iblog.dto.user.SystemUserLoginQry;
import com.xianyun.site.iblog.dto.user.data.SystemUserDTO;
import com.xianyun.site.iblog.gatewayimpl.database.SystemUserMapper;
import com.xianyun.site.iblog.gatewayimpl.database.domainobject.SystemUserDO;
import com.xianyun.site.iblog.user.executor.handle.BaseLoginCheckHandle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 用户名密码登录处理
 * @author mac_zyj
 */
@Slf4j
@Component
public class IUserPasswordCheckHandle extends BaseLoginCheckHandle {

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public SystemUserDTO loginExecute(SystemUserLoginQry systemUserLoginQry) {
        SystemUserDO searchData = selectBaseUserByCondition(systemUserLoginQry.getExtendKey());
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        if (null != searchData){
            if (passwordEncoder.matches(systemUserLoginQry.getCredentials(),searchData.getPassword())){
                return SystemUserConvertor.toSystemUserDTO(searchData);
            }
            else {
                log.debug("userName:{},-- 用户名或密码错误",systemUserLoginQry.getExtendKey());
                throw new LoginCheckErrorException("用户名或密码错误");
            }
        }
        throw new UserNotRegisterException("BIZ_CLOUD_BLOG_LOGIN");
    }

    /**
     * 查询用户是否存在
     * @param condition 条件
     * @return 查询结果
     */
    private SystemUserDO selectBaseUserByCondition(String condition) {
        if (FormatUtils.isEmail(condition)){
            return systemUserMapper.getSystemUserByEmail(condition);
        } else if (FormatUtils.isNumLegal(condition)){
            return systemUserMapper.getSystemUserByMobile(condition);
        } else {
            return systemUserMapper.getSystemUserByName(condition);
        }
    }
}
